using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using IdentityServer4.EntityFramework.Interfaces;
using IdentityServer4.EntityFramework.Options;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZFY.UMC.API.Model.Model;
using UserClaim = ZFY.UMC.API.Model.Model.UserClaim;

namespace ZFY.UMC.API.Model
{
    public class ZFYIdentityDbContext : IdentityDbContext<User, Role, Guid, UserClaim,
    UserRole, IdentityUserLogin<Guid>,
    IdentityRoleClaim<Guid>, IdentityUserToken<Guid>>
    {

        public ZFYIdentityDbContext(DbContextOptions<ZFYIdentityDbContext> options)
            : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<UserRole>(userRole =>
            {
                userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

                userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
            });
            builder.Entity<User>(user =>
            {
                user.HasMany(x => x.UserRoles).WithOne(x => x.User);
                user.HasMany(x => x.Claims).WithOne().HasForeignKey(x => x.UserId).IsRequired();
                user.OwnsOne(x => x.Address);
            });
            builder.Entity<Role>(role =>
            {
                role.HasMany(x => x.UserRoles).WithOne(x => x.Role);
            });
            
        }
    }
    [Table("ApiResources")]
    public class ZFYApiResource : IdentityServer4.EntityFramework.Entities.ApiResource
    {
        public string ApiUrl { get; set; }
    }
    public class ZFYConfigurationDbContext : ConfigurationDbContext<ZFYConfigurationDbContext>
    {
        new public DbSet<ZFYApiResource> ApiResources
        {
            get;
            set;
        }

        public ZFYConfigurationDbContext(DbContextOptions<ZFYConfigurationDbContext> options, ConfigurationStoreOptions storeOptions)
            : base(options, storeOptions)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

        }
    }
}
